﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using ElectronicCommerce.Framework.ServiceModel.Configuration;
using ElectronicCommerce.Framework.ServiceModel.WCF.TransferElement;
using ElectronicCommerce.Framework.Utility;

namespace ElectronicCommerce.Framework.ServiceModel.WCF
{
    public class ClientChannelFactory<T> : ChannelFactory<T>
    {
        #region [ Privates ]

        private string serviceName;

        #endregion

        #region [ Constructors ]

        public ClientChannelFactory()
            : this(typeof(T).Name)
        {
        }

        public ClientChannelFactory(string serviceName)
            : base(typeof(T))
        {
            this.serviceName = serviceName;
            base.InitializeEndpoint((string)null, null);
        }

        #endregion

        protected override void ApplyConfiguration(string configurationName)
        {
        }

        public override T CreateChannel(EndpointAddress address, Uri via)
        {
            return base.CreateChannel(address, via);
        }

        protected override ServiceEndpoint CreateDescription()
        {
            ServiceEndpoint endpoint = base.CreateDescription();
            endpoint.Name = this.serviceName;
            //ServiceEndpoint endpoint = new ServiceEndpoint(new ContractDescription(serviceName));
            ServiceElement serviceElement =
                ServiceModelConfigHelper.ServiceConfig.GetMixServiceElement(typeof(T), this.serviceName);

            IGetBindingByConfig handler = BindingFactory.CreateHandler(
                EnumHelper.GetEnumObject<BindingTypeEnum>(serviceElement.Binding.Type));

            endpoint.Binding = handler.GetBindingMsgByConfig(serviceElement.Binding.Content);

            string address = String.Format("{0}/{1}",
                serviceElement.Server.Address.Trim().TrimEnd('/'),
                serviceElement.RelativeAddress.Trim().TrimStart('/'));
            endpoint.Address = new EndpointAddress(handler.GetAddress(address));

            return endpoint;
        }

        protected override IChannelFactory CreateFactory()
        {
            return base.CreateFactory();
        }

        protected override TimeSpan DefaultCloseTimeout
        {
            get
            {
                return base.DefaultCloseTimeout;
            }
        }

        protected override TimeSpan DefaultOpenTimeout
        {
            get
            {
                return base.DefaultOpenTimeout;
            }
        }
    }
}
